package user;

import utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "EmailComfirmServlet")
public class EmailComfirmServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    private void goFailPage(HttpServletResponse response){
        String site = "/login.html"; // TODO: 填写错误页面url
        response.setStatus(response.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", site);
    }

    private void goSuccessPage(HttpServletResponse response){
        String site = "/index.html"; // TODO: 填写成功页面url
        response.setStatus(response.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", site);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        String type = request.getParameter("type");
        String email = request.getParameter("email");
        String vcode = request.getParameter("code");

        if (type == null || type.isEmpty()){
            goFailPage(response);
            return;
        }

        if (email == null || email.isEmpty()){
            goFailPage(response);
            return;
        }

        if (vcode == null || vcode.isEmpty()){
            goFailPage(response);
            return;
        }

        ResultSet resultSet = (new MysqlUtils()).getEmailVerify(email);

        if (resultSet == null){
            goFailPage(response);
            return;
        }

        try {
            String emailVtime = resultSet.getString(2);
            long time = Long.parseLong(emailVtime);
            if (System.currentTimeMillis() - time > 3600000){
                goFailPage(response);
                return;
            }

            String emailVcode = resultSet.getString(1);
            if (!emailVcode.equals(vcode)){
                goFailPage(response);
                return;
            }

            if (!(new MysqlUtils()).comfirmEmail(email)){
                goFailPage(response);
                return;
            }

            switch (type){
                case "reg":
                    goSuccessPage(response);
                    break;
                case "forget":
                    // TODO: 前往重置密码页面
                    break;
                default:
                    goFailPage(response);
                    break;
            }


        } catch (Exception e) {
            e.printStackTrace();
            goFailPage(response);
        }


    }
}
